package com.tyj.movie.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * 日期: 2021/6/5 8:41
 * 作者: 谭友杰
 * 类说明:
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    BCryptPasswordEncoder passwordEncoder;

    @Autowired
    UserDetailsService userDetailsService;

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    /**
     * 定义认证规则
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //使用自定义认证
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //权限管理================================================================
        http.authorizeRequests()
                .antMatchers("/login.html").permitAll()
                .antMatchers("/css/**").permitAll()
                .antMatchers("/fonts/**").permitAll()
                .antMatchers("/images/**").permitAll()
                .antMatchers("/js/**").permitAll()
                .antMatchers("/zs/**").permitAll()
                .antMatchers("/movieTables/**").permitAll()

                .anyRequest().authenticated();


        //登录管理================================================================
        http.formLogin()
                .passwordParameter("password")  //对应前端数据
                .usernameParameter("username")  //对应前端数据
                .loginPage("/login.html")  //指定登录页面
                .defaultSuccessUrl("/") //登录成功默认跳转页面
                .loginProcessingUrl("/movie/admin/login") //处理登录请求
                .failureForwardUrl("/movie/admin/loginError"); //指定登录失败跳转的地址

//      关闭跨站点请求伪造 默认是开启的
        http.csrf().disable();

        //退出管理================================================================
        http.logout().logoutUrl("/logout").     //退出请求
                logoutSuccessUrl("/login.html").    //退出返回页面
                deleteCookies("JSESSIONID");        //删除session

    }

}






